using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace SystemScanner.ClientServices
{
	public class InstalledServicesService
	{
		public static void AddServicesToScan(SystemScanner.Data.Scan scan)
		{
			foreach (var svc in GetInstalledServices())
			{
				if (scan.ScanServices.Any(x => x.Service.Identifier == svc.Service.Identifier) == false)
				{
					scan.ScanServices.Add(svc);
				}
			}
		}
        public static IEnumerable<Data.ScanService> GetInstalledServices()
		{
			/// Usually, Many to Many would be more or less handled automatically
			/// by EF. But ScanService defines a M-M relationship between
			/// the Scan and Service tables, but also has some attributes
			/// of its own. This means that we have to add both entities
			/// fairly manually. 

			foreach (var item in WmiService.GetInstancesOfClass("Win32_Service"))
			{
				var ss = new Data.ScanService
				{
					LogonName = item["StartName"] as string,
					StartMode = item["StartMode"] as string,
					State = item["State"] as string,
					Status = item["Status"] as string
				};
				var erv = new Data.Service
				{
					Identifier = item["Name"] as string,
					Name = item["DisplayName"] as string
				};
				ss.Service = erv;
				yield return ss;
			}
		}
	}
}
